package com.app.twth.ui.checkin;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.airsaid.pickerviewlibrary.TimePickerView;
import com.app.twth.BR;
import com.app.twth.R;
import com.app.twth.app.AppRouter;
import com.app.twth.app.Constant;
import com.app.twth.app.MyApplication;
import com.app.twth.base.BaseCameraPhotoActivity;
import com.app.twth.bean.FilePathListDTO;
import com.app.twth.bean.PhotoBean;
import com.app.twth.databinding.ActivityCheckinBinding;
import com.app.twth.databinding.DialogCheckinContainerBinding;
import com.app.twth.ui.checkin.submit.CheckinSubmitActivity;
import com.app.twth.utils.DateUtil;
import com.app.twth.utils.DividerItemDecoration;
import com.app.twth.utils.MyDialogUtil;
import com.app.twth.utils.ToastUtil;
import com.app.twth.utils.Utils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

/**
 * Created by admin on 2024/5/7.
 * Description:
 * Encoding: utf-8
 */
public class CheckinActivity extends BaseCameraPhotoActivity<ActivityCheckinBinding, CheckinViewModel> {
    private String TAG = getClass().getSimpleName();
    private int type = 0;
    private int position = 0;
    private List<PhotoBean> bolPaths = new ArrayList<>();
    private List<PhotoBean> doorPaths = new ArrayList<>();
    private List<PhotoBean> sealPaths = new ArrayList<>();
    private List<PhotoBean> openPaths = new ArrayList<>();
    private List<PhotoBean> damagePaths = new ArrayList<>();
    private PhotoAdapter bolAdapter, doorAdapter, sealAdapter, openAdapter, damageAdapter;

    @Override
    protected int initViewModelId() {
        return BR.viewModel;
    }

    @Override
    protected void initData() {
        setResetGone();
//        setReset(getString(R.string.complete));
        setNext(getString(R.string.next));

        viewModel.getSelectList();

        bolPaths.add(new PhotoBean());
        bolAdapter = new PhotoAdapter(this, bolPaths, 1, position -> {
            type = 0;
            this.position = position;
            requestCamera("bol");
        }, str -> {
            type = 0;
        });
        GridLayoutManager bolManager = new GridLayoutManager(this, 3);
        binding.rvBol.setLayoutManager(bolManager);
        binding.rvBol.setAdapter(bolAdapter);

        doorPaths.add(new PhotoBean());
        doorAdapter = new PhotoAdapter(this, doorPaths, 1, position -> {
            type = 1;
            this.position = position;
            requestCamera("door");
        }, str -> {
            type = 1;
        });
        GridLayoutManager doorManager = new GridLayoutManager(this, 3);
        binding.rvDoor.setLayoutManager(doorManager);
        binding.rvDoor.setAdapter(doorAdapter);

        sealPaths.add(new PhotoBean());
        sealAdapter = new PhotoAdapter(this, sealPaths, 1, position -> {
            type = 2;
            this.position = position;
            requestCamera("seal");
        }, str -> {
            type = 2;
        });
        GridLayoutManager sealManager = new GridLayoutManager(this, 3);
        binding.rvSeal.setLayoutManager(sealManager);
        binding.rvSeal.setAdapter(sealAdapter);

        openPaths.add(new PhotoBean());
        openAdapter = new PhotoAdapter(this, openPaths, 1, position -> {
            type = 3;
            this.position = position;
            requestCamera("open");
        }, str -> {
            type = 3;
        });
        GridLayoutManager openManager = new GridLayoutManager(this, 3);
        binding.rvOpen.setLayoutManager(openManager);
        binding.rvOpen.setAdapter(openAdapter);

        damagePaths.add(new PhotoBean());
        damageAdapter = new PhotoAdapter(this, damagePaths, 1, position -> {
            type = 4;
            this.position = position;
            requestCamera("damaged");
        }, str -> {
            type = 4;
        });
        GridLayoutManager damageManager = new GridLayoutManager(this, 3);
        binding.rvDamaged.setLayoutManager(damageManager);
        binding.rvDamaged.setAdapter(damageAdapter);
    }

    @Override
    protected void initListener() {
        viewModel.errorResultCode.observe(this, code -> {
            showHint((String) code);
        });
        viewModel.infoResultCode.observe(this, code -> {
            if (viewModel.containerInfo.getFilePathList() != null) {
                for (FilePathListDTO filePathListDTO : viewModel.containerInfo.getFilePathList()) {
                    List<String> pathList = filePathListDTO.getPathList();
                    if (pathList != null && pathList.size() > 0) {
                        if (filePathListDTO.getName().equals("bol")) {
                            setPath(0, pathList.get(0));
                        } else if (filePathListDTO.getName().equals("door")) {
                            setPath(1, pathList.get(0));
                        } else if (filePathListDTO.getName().equals("seal")) {
                            setPath(2, pathList.get(0));
                        } else if (filePathListDTO.getName().equals("open")) {
                            setPath(3, pathList.get(0));
                        } else if (filePathListDTO.getName().equals("damaged")) {
                            setPath(4, pathList.get(0));
                        }
                    }
                }
            }
        });
        viewModel.fileUploadMutableLiveData.observe(this, data -> {
            Log.e(TAG, "type():" + data.getType() + ",position:" + data.getPosition());
            switch (data.getType()) {
                case 0:
                    if (bolPaths.size() > data.getPosition()) {
                        PhotoBean photoBean = bolPaths.get(data.getPosition());
                        photoBean.setUrlImg(data.getPath());
                    }
                    break;
                case 1:
                    if (doorPaths.size() > data.getPosition()) {
                        PhotoBean photoBean = doorPaths.get(data.getPosition());
                        photoBean.setUrlImg(data.getPath());
                    }
                    break;
                case 2:
                    if (sealPaths.size() > data.getPosition()) {
                        PhotoBean photoBean = sealPaths.get(data.getPosition());
                        photoBean.setUrlImg(data.getPath());
                    }
                    break;
                case 3:
                    if (openPaths.size() > data.getPosition()) {
                        PhotoBean photoBean = openPaths.get(data.getPosition());
                        photoBean.setUrlImg(data.getPath());
                    }
                    break;
                case 4:
                    if (damagePaths.size() > data.getPosition()) {
                        PhotoBean photoBean = damagePaths.get(data.getPosition());
                        photoBean.setUrlImg(data.getPath());
                    }
                    break;
            }

            if (data.isSubmit()) {
                submitData();
            }
        });

        viewModel.checkinSubmitMutableLiveData.observe(this, code -> {

            Bundle bundle = new Bundle();
            bundle.putSerializable("Container", viewModel.container);

            AppRouter.showActivityForResult(mContext, CheckinSubmitActivity.class, bundle, Constant.ForResult2);
        });

        viewModel.isLoading.observe(this, b -> {
            if (b.isShow()) {
                showProgressDialog(b.getMsg());
            } else {
                dismissProgressDialog();
            }
        });
    }

    @Override
    protected String setTitle() {
        return "Checkin";
    }

    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_reset:
                break;
            case R.id.tv_next:
                if (System.currentTimeMillis() - timeMillis < spaceTime) {
                    return;
                }
                timeMillis = System.currentTimeMillis();
                submitData();
                break;
            case R.id.layout_time:
                showDate();
                break;
            case R.id.layout_select_container:
                if ((viewModel.containers == null) || (viewModel.containers.size() == 0)) {
                    return;
                }
                showTallyDetailDialog();
                break;
        }
    }


    private void resetDate() {
        bolPaths.clear();
        bolPaths.add(new PhotoBean());
        bolAdapter.notifyDataSetChanged();

        doorPaths.clear();
        doorPaths.add(new PhotoBean());
        doorAdapter.notifyDataSetChanged();

        sealPaths.clear();
        sealPaths.add(new PhotoBean());
        sealAdapter.notifyDataSetChanged();

        openPaths.clear();
        openPaths.add(new PhotoBean());
        openAdapter.notifyDataSetChanged();

        damagePaths.clear();
        damagePaths.add(new PhotoBean());
        damageAdapter.notifyDataSetChanged();

    }

    private void showDate() {
        final TimePickerView pvTime = new TimePickerView(mContext, TimePickerView.Type.YEAR_MONTH_DAY);
        pvTime.setCancelTextColor(R.color.color_666666);
        pvTime.setOnTimeSelectListener(date -> {
            try {
                String timeFormat = new SimpleDateFormat("20yy-MM-dd", Locale.getDefault()).format(date);
                String replace = timeFormat.replace("-", "");
                String newDate = DateUtil.getFormatDate();
//                if (Integer.parseInt(replace) > Integer.parseInt(newDate)) {
//                    ToastUtil.showToast("You can't choose the future");
//                    return;
//                }
                if (viewModel.container != null) {
                    String receiptDatetime = viewModel.container.getCheckinDatetime();
                    if (!Utils.isEmpty(receiptDatetime)) {
                        receiptDatetime = DateUtil.utcToLocal(receiptDatetime);
                        newDate = receiptDatetime.replace("-", "");
                        if (Integer.parseInt(replace) > Integer.parseInt(newDate)) {
                            ToastUtil.showToast("Beyond the time of receipt");
                            return;
                        }
                    }
                }
                viewModel.mTime.setValue(timeFormat);
            } catch (Exception e) {
                e.printStackTrace();
            }

        });
        pvTime.show();
    }

    private AlertDialog dialogTallyDetail;

    private void showTallyDetailDialog() {
        dialogTallyDetail = MyDialogUtil.getDialog(mContext, initTallyDetailDialogView(), Gravity.TOP);
        dialogTallyDetail.setCanceledOnTouchOutside(true);
        dialogTallyDetail.show();
    }

    boolean isasc = false;
    CheckinContainerAdapter tallyDetailAdapter;

    private View initTallyDetailDialogView() {
        isasc = false;
        DialogCheckinContainerBinding dialogBinding = DialogCheckinContainerBinding.inflate(LayoutInflater.from(MyApplication.getAppInstance()));
        dialogBinding.tvSort.setOnClickListener(v -> {
            try {
                if (isasc) {
                    dialogBinding.ivUp.setImageDrawable(MyApplication.getAppInstance().getResources().getDrawable(R.drawable.ic_barrow_drop_up_gray));
                    dialogBinding.ivDown.setImageDrawable(MyApplication.getAppInstance().getResources().getDrawable(R.drawable.ic_arrow_drop_down));
                } else {
                    dialogBinding.ivUp.setImageDrawable(MyApplication.getAppInstance().getResources().getDrawable(R.drawable.ic_barrow_drop_up));
                    dialogBinding.ivDown.setImageDrawable(MyApplication.getAppInstance().getResources().getDrawable(R.drawable.ic_arrow_drop_down_gray));
                }
                isasc = !isasc;
                Collections.reverse(viewModel.containers);
                if (tallyDetailAdapter != null) {
                    tallyDetailAdapter.setData(viewModel.containers);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        });
        tallyDetailAdapter = new CheckinContainerAdapter(MyApplication.getAppInstance(), viewModel.containers, position -> {
            resetDate();
            viewModel.container = position;
            viewModel.getCheckinInfo();
            viewModel.code.setValue(viewModel.container.getContainerNo());
            binding.setLifecycleOwner(this);//需要加上这句,否则不会刷新UI

            if (!Utils.isEmpty(viewModel.container.getCheckinDatetime())) {
                if (viewModel.container.getCheckinDatetime().contains("T")) {
                    viewModel.mTime.setValue(viewModel.container.getCheckinDatetime().substring(0, viewModel.container.getCheckinDatetime().indexOf("T")));
                } else {
                    viewModel.mTime.setValue(viewModel.container.getCheckinDatetime());
                }
            }
            if (dialogTallyDetail != null) {
                dialogTallyDetail.dismiss();
            }
        }
        );
        dialogBinding.tvCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String container = dialogBinding.tvCode.getText().toString();
                if (Utils.isEmpty(container)) {
                    tallyDetailAdapter.setData(viewModel.containers);
                } else {
                    ArrayList<Container> receivings = new ArrayList<>();
                    for (Container receiving : viewModel.containers) {
                        if (receiving.getContainerNo().toLowerCase().contains(container.toLowerCase())) {
                            receivings.add(receiving);
                        }
                    }
                    tallyDetailAdapter.setData(receivings);
                }
            }
        });

        LinearLayoutManager layoutManager1 = new LinearLayoutManager(MyApplication.getAppInstance());
        layoutManager1.setOrientation(LinearLayoutManager.VERTICAL);
        dialogBinding.recyclerviewDetail.setLayoutManager(layoutManager1);
        //添加装饰类
        dialogBinding.recyclerviewDetail.addItemDecoration(new DividerItemDecoration(MyApplication.getAppInstance(), DividerItemDecoration.VERTICAL_LIST));
        dialogBinding.recyclerviewDetail.setAdapter(tallyDetailAdapter);

        return dialogBinding.getRoot();
    }

    @Override
    protected void getImgPath(String pathImage) {
        setPath(type, pathImage);
    }

    private void setCameraPhotoOrShow(ImageView iv_delete, String path, String name) {
        temp_path = path;
        if (iv_delete.getVisibility() == View.VISIBLE) {
            showPhotoDialog(temp_path);
        } else {
            requestCamera(name);
        }
    }

    private void setPath(int type, String pathImage) {
        Log.e(TAG, "setPath>type:" + type + ",pathImage:" + pathImage);

        if (!pathImage.contains("http")) {//选择的图片
            String fileName = "";
            switch (type) {
                case 0:
                    fileName = "bol";
                    break;
                case 1:
                    fileName = "door";
                    break;
                case 2:
                    fileName = "seal";
                    break;
                case 3:
                    fileName = "open";
                    break;
                case 4:
                    fileName = "damaged";
                    break;
            }
            Log.e(TAG, "setPath>type:" + type + ",fileName:" + fileName);
            viewModel.fileUpload(viewModel.code.getValue(), fileName, pathImage, type, 0, false, false);
        }

        PhotoBean imgUrl = new PhotoBean();
        imgUrl.setPathImg(pathImage);
        imgUrl.setUrlImg(pathImage);
        switch (type) {
            case 0:
                if (bolPaths.size() > position) {
                    bolPaths.remove(position);
                    bolPaths.add(position, imgUrl);
                }
                if (bolPaths.size() < 1) {
                    if (!Utils.isEmpty(bolPaths.get(bolPaths.size() - 1).getPathImg())) {
                        doorPaths.add(new PhotoBean());
                    }
                }
                for (PhotoBean img : bolPaths) {
                    Log.e(TAG, img.toString());
                }
                if (bolAdapter != null) {
                    bolAdapter.setData(bolPaths);
                }
                break;
            case 1:
                if (doorPaths.size() > position) {
                    doorPaths.remove(position);
                    doorPaths.add(position, imgUrl);
                }
                if (doorPaths.size() < 1) {
                    if (!Utils.isEmpty(doorPaths.get(doorPaths.size() - 1).getPathImg())) {
                        doorPaths.add(new PhotoBean());
                    }
                }
                for (PhotoBean img : doorPaths) {
                    Log.e(TAG, img.toString());
                }
                if (doorAdapter != null) {
                    doorAdapter.setData(doorPaths);
                }
                break;
            case 2:
                if (sealPaths.size() > position) {
                    sealPaths.remove(position);
                    sealPaths.add(position, imgUrl);
                }
                if (sealPaths.size() < 1) {
                    if (!Utils.isEmpty(sealPaths.get(sealPaths.size() - 1).getPathImg())) {
                        sealPaths.add(new PhotoBean());
                    }
                }
                for (PhotoBean img : sealPaths) {
                    Log.e(TAG, img.toString());
                }
                if (sealAdapter != null) {
                    sealAdapter.setData(sealPaths);
                }
                break;
            case 3:
                if (openPaths.size() > position) {
                    openPaths.remove(position);
                    openPaths.add(position, imgUrl);
                }
                if (openPaths.size() < 1) {
                    if (!Utils.isEmpty(openPaths.get(openPaths.size() - 1).getPathImg())) {
                        openPaths.add(new PhotoBean());
                    }
                }
                for (PhotoBean img : openPaths) {
                    Log.e(TAG, img.toString());
                }
                if (openAdapter != null) {
                    openAdapter.setData(openPaths);
                }
                break;
            case 4:
                if (damagePaths.size() > position) {
                    damagePaths.remove(position);
                    damagePaths.add(position, imgUrl);
                }
                if (damagePaths.size() < 1) {
                    if (!Utils.isEmpty(damagePaths.get(damagePaths.size() - 1).getPathImg())) {
                        damagePaths.add(new PhotoBean());
                    }
                }
                for (PhotoBean img : damagePaths) {
                    Log.e(TAG, img.toString());
                }
                if (damageAdapter != null) {
                    damageAdapter.setData(damagePaths);
                }
                break;
        }
    }


    private void submitData() {
        if (Utils.isEmpty(viewModel.code.getValue())) {
            ToastUtil.showToast("Scan container number/container code");
            return;
        }
        if (Utils.isEmpty(viewModel.mTime.getValue())) {
            ToastUtil.showToast("Please select Drop Date");
            return;
        }

        List<String> bolPathList = new ArrayList<>();
        if (bolPaths.size() > 0) {
            for (int i = 0; i < bolPaths.size(); i++) {
                PhotoBean photoBean = bolPaths.get(i);
                String s = photoBean.getUrlImg();
                Log.e(TAG, "s:" + photoBean.toString());
                if (!Utils.isEmpty(s)) {
                    if (!s.contains("http")) {
                        position = i;
                        viewModel.fileUpload(viewModel.code.getValue(), "bol", s, 0, position, true, true);
                        return;
                    }
                    bolPathList.add(s);
                } else if (!Utils.isEmpty(photoBean.getPathImg())) {
                    position = i;
                    viewModel.fileUpload(viewModel.code.getValue(), "bol", photoBean.getPathImg(), 0, position, true, true);
                    return;
                }
            }
        }
        if (bolPathList.size() == 0) {
            ToastUtil.showToast("Please add bol photos");
            return;
        }

        List<String> doorPathList = new ArrayList<>();
        if (doorPaths.size() > 0) {
            for (int i = 0; i < doorPaths.size(); i++) {
                PhotoBean photoBean = doorPaths.get(i);
                String s = photoBean.getUrlImg();
                Log.e(TAG, "s:" + photoBean.toString());
                if (!Utils.isEmpty(s)) {
                    if (!s.contains("http")) {
                        position = i;
                        viewModel.fileUpload(viewModel.code.getValue(), "door", s, 1, position, true, true);
                        return;
                    }
                    doorPathList.add(s);
                } else if (!Utils.isEmpty(photoBean.getPathImg())) {
                    position = i;
                    viewModel.fileUpload(viewModel.code.getValue(), "door", photoBean.getPathImg(), 1, position, true, true);
                    return;
                }
            }
        }
        if (doorPathList.size() == 0) {
            ToastUtil.showToast("Please add door photos");
            return;
        }

        List<String> sealPathList = new ArrayList<>();
        if (sealPaths.size() > 0) {
            for (int i = 0; i < sealPaths.size(); i++) {
                PhotoBean photoBean = sealPaths.get(i);
                String s = photoBean.getUrlImg();
                Log.e(TAG, "s:" + photoBean.toString());
                if (!Utils.isEmpty(s)) {
                    if (!s.contains("http")) {
                        position = i;
                        viewModel.fileUpload(viewModel.code.getValue(), "seal", s, 2, position, true, true);
                        return;
                    }
                    sealPathList.add(s);
                } else if (!Utils.isEmpty(photoBean.getPathImg())) {
                    position = i;
                    viewModel.fileUpload(viewModel.code.getValue(), "seal", photoBean.getPathImg(), 2, position, true, true);
                    return;
                }
            }
        }
        if (sealPathList.size() == 0) {
            ToastUtil.showToast("Please add seal photos");
            return;
        }

        List<String> openPathList = new ArrayList<>();
        if (openPaths.size() > 0) {
            for (int i = 0; i < openPaths.size(); i++) {
                PhotoBean photoBean = openPaths.get(i);
                String s = photoBean.getUrlImg();
                Log.e(TAG, "s:" + photoBean.toString());
                if (!Utils.isEmpty(s)) {
                    if (!s.contains("http")) {
                        position = i;
                        viewModel.fileUpload(viewModel.code.getValue(), "open", s, 3, position, true, true);
                        return;
                    }
                    openPathList.add(s);
                } else if (!Utils.isEmpty(photoBean.getPathImg())) {
                    position = i;
                    viewModel.fileUpload(viewModel.code.getValue(), "open", photoBean.getPathImg(), 3, position, true, true);
                    return;
                }
            }
        }
        if (openPathList.size() == 0) {
            ToastUtil.showToast("Please add open photos");
            return;
        }

        List<String> damagedPathList = new ArrayList<>();
        if (damagePaths.size() > 0) {
            for (int i = 0; i < damagePaths.size(); i++) {
                PhotoBean photoBean = damagePaths.get(i);
                String s = photoBean.getUrlImg();
                Log.e(TAG, "s:" + photoBean.toString());
                if (!Utils.isEmpty(s)) {
                    if (!s.contains("http")) {
                        position = i;
                        viewModel.fileUpload(viewModel.code.getValue(), "damaged", s, 4, position, true, true);
                        return;
                    }
                    damagedPathList.add(s);
                } else if (!Utils.isEmpty(photoBean.getPathImg())) {
                    position = i;
                    viewModel.fileUpload(viewModel.code.getValue(), "damaged", photoBean.getPathImg(), 4, position, true, true);
                    return;
                }
            }
        }

        ContainerInfo containerInfo = new ContainerInfo();
        List<FilePathListDTO> filePathList = new ArrayList<>();

        FilePathListDTO bolFilePathListDTO = new FilePathListDTO();
        bolFilePathListDTO.setName("bol");
        bolFilePathListDTO.setPathList(bolPathList);
        filePathList.add(bolFilePathListDTO);

        FilePathListDTO doorFilePathListDTO = new FilePathListDTO();
        doorFilePathListDTO.setName("door");
        doorFilePathListDTO.setPathList(doorPathList);
        filePathList.add(doorFilePathListDTO);

        FilePathListDTO sealFilePathListDTO = new FilePathListDTO();
        sealFilePathListDTO.setName("seal");
        sealFilePathListDTO.setPathList(sealPathList);
        filePathList.add(sealFilePathListDTO);

        FilePathListDTO openFilePathListDTO = new FilePathListDTO();
        openFilePathListDTO.setName("open");
        openFilePathListDTO.setPathList(openPathList);
        filePathList.add(openFilePathListDTO);

        if (damagedPathList.size() > 0) {
            FilePathListDTO damagedFilePathListDTO = new FilePathListDTO();
            damagedFilePathListDTO.setName("damaged");
            damagedFilePathListDTO.setPathList(damagedPathList);
            filePathList.add(damagedFilePathListDTO);
        }

        containerInfo.setId(viewModel.container.getId());
        containerInfo.setArrivedDate(viewModel.mTime.getValue());
        containerInfo.setFilePathList(filePathList);

        viewModel.checkinNext(containerInfo);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.ForResult2 && resultCode == RESULT_OK) {
            clearData();
            viewModel.getSelectList();
        }
    }

    private void clearData() {
        try {
            Log.e(TAG, "clearData");
            bottomLayoutBinding.tvHint.setText("");
            viewModel.code.setValue("");
            viewModel.mTime.setValue("");
            resetDate();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
